package com.panda.web.service.commons.impl;

import com.panda.web.domain.dto.TrendDTO;
import com.panda.web.domain.vo.commons.BackGroundVO;
import com.panda.web.domain.vo.commons.TrendVO;
import com.panda.web.entity.order.WechatOrder;
import com.panda.web.entity.product.Product;
import com.panda.web.mapper.order.WechatOrderMapper;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.product.ProductMapper;
import com.panda.web.mapper.py.JobMapper;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.mapper.wechatinfo.WechatUserinfoMapper;
import com.panda.web.service.commons.BackgroundService;
import com.wechat.pay.java.service.weixinpayscanandride.model.OrderAmount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class BackgroundServiceImpl implements BackgroundService {

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WechatUserinfoMapper userinfoMapper;
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private WechatOrderMapper orderMapper;
    @Autowired
    private OpenidProductMapper openidProductMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 后台首页
     *
     * @return
     */
    @Override
    public BackGroundVO getHomePage() {
        BackGroundVO vo = new BackGroundVO();
        int appraisalCount = openidProductMapper.selectListAndPAAndStatus();//购买测评报告未退款的数量
        vo.setAppraisalCount(appraisalCount);
        BigDecimal paymentAmount = orderMapper.selectYZFWTK(); //待修改 TODO
        vo.setPaymentAmount(paymentAmount);
        Long userinfoCount = userinfoMapper.selectCount(null);
        vo.setUserinfoCount(userinfoCount);
        //TODO AI
        int i = openidProductMapper.selectListAIAndStatus();
        vo.setAiCustomization(i);
        Long wechatUserCount = wechatUserMapper.selectCount(null);
        vo.setWechatUserCount(wechatUserCount);
        int jobCount = jobMapper.selectCountByApply();
        vo.setJobCount(jobCount);

        vo.setOnlineNumber(generateRandomNumber());
        return vo;
    }
    // 生成随机数的接口
    public static int generateRandomNumber() {
        Random random = new Random();
        return random.nextInt(51) + 350;  // 生成一个范围在 350 到 400 之间的随机数
    }
    /**
     * 返回图标
     *
     * @param dto
     * @return
     */
    @Override
    public BackGroundVO getTrend(TrendDTO dto) {
        BackGroundVO backGroundVO = new BackGroundVO();
        List<Product> productList = productMapper.selectList(null);

        if (productList != null && !productList.isEmpty()) {

            List<TrendVO>dayList = new ArrayList<>();
            for (Product product : productList) {
                TrendVO trendVO = new TrendVO();

                trendVO.setName(product.getProductName());
                List<String> dayaList = new ArrayList<>();
                List<Integer> countList = new ArrayList<>();
                if (Objects.equals(dto.getDay(), "1")) {
                    // 今日数据
                    String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Integer count = orderMapper.findByProductId(product.getProductId(), today);
                    dayaList.add(today);
                    countList.add(count);
                } else if (Objects.equals(dto.getDay(), "2")) {
                    // 本月数据
                    List<String> daysOfCurrentMonth = getDaysOfCurrentMonth();
                    for (String today : daysOfCurrentMonth) {
                        Integer count = orderMapper.findByProductId(product.getProductId(), today);
                        dayaList.add(today);
                        countList.add(count);
                    }
                } else if (Objects.equals(dto.getDay(), "3")) {
                    // 本年数据
                    LocalDate now = LocalDate.now();
                    int currentYear = now.getYear(); // 获取当前年份

                    for (int month = 1; month <= 12; month++) {
                        // 获取每个月的第一天和最后一天
                        LocalDate firstDayOfMonth = LocalDate.of(currentYear, month, 1);
                        LocalDate lastDayOfMonth = firstDayOfMonth.withDayOfMonth(firstDayOfMonth.lengthOfMonth());

                        // 将日期转换为 LocalDateTime，并添加时间部分
                        LocalDateTime firstDayOfMonthWithTime = firstDayOfMonth.atStartOfDay(); // 00:00:00
                        LocalDateTime lastDayOfMonthWithTime = lastDayOfMonth.atTime(23, 59, 59); // 23:59:59

                        // 格式化日期时间
                        String startTime = firstDayOfMonthWithTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        String endTime = lastDayOfMonthWithTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

                        // 查询当前月的订单数量
                        Integer count = orderMapper.findByProductIdBETWEEN(product.getProductId(), startTime, endTime);
                        // 添加到列表
                        dayaList.add(month + "月");
                        countList.add(count != null ? count : 0); // 防止 count 为 null，默认 0
                    }


                }else if (Objects.equals(dto.getDay(), "4")) {
                    // 自定义时间区间数据
                    String startTime = dto.getStartTime(); // 假设 startTime 为 "2025-02"
                    String endTime = dto.getEndTime(); // 假设 endTime 为 "2025-04"

                    // 解析年月
                    int startYear = Integer.parseInt(startTime.split("-")[0]);
                    int startMonth = Integer.parseInt(startTime.split("-")[1]);
                    int endYear = Integer.parseInt(endTime.split("-")[0]);
                    int endMonth = Integer.parseInt(endTime.split("-")[1]);

                    // 遍历从 startMonth 到 endMonth 的所有月份
                    for (int month = startMonth; month <= endMonth; month++) {
                        // 如果跨年，处理年份的变化
                        int currentYear = (month > 12) ? startYear + 1 : startYear;
                        if (month > 12) month -= 12;

                        // 获取该月的第一天和最后一天
                        LocalDate firstDayOfMonth = LocalDate.of(currentYear, month, 1);
                        LocalDate lastDayOfMonth = firstDayOfMonth.withDayOfMonth(firstDayOfMonth.lengthOfMonth());

                        // 将日期转换为 LocalDateTime，并添加时间部分
                        LocalDateTime firstDayOfMonthWithTime = firstDayOfMonth.atStartOfDay(); // 00:00:00
                        LocalDateTime lastDayOfMonthWithTime = lastDayOfMonth.atTime(23, 59, 59); // 23:59:59

                        // 格式化日期时间
                        String formattedStartTime = firstDayOfMonthWithTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        String formattedEndTime = lastDayOfMonthWithTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

                        // 查询当前月的订单数量
                        Integer count = orderMapper.findByProductIdBETWEEN(product.getProductId(), formattedStartTime, formattedEndTime);

                        // 添加到列表
                        dayaList.add(month + "月");
                        countList.add(count != null ? count : 0); // 防止 count 为 null，默认 0
                    }
                }

                trendVO.setCountList(countList);
                trendVO.setDayList(dayaList);
                dayList.add(trendVO);
                backGroundVO.setDayList(dayList);
            }
        }

        return backGroundVO;
    }


    public static List<String> getDaysOfCurrentMonth() {
        List<String> daysList = new ArrayList<>();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取当前月份的第一天
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);

        // 获取当前月份的最后一天
        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 遍历从第一天到最后一天
        for (LocalDate date = firstDayOfMonth; !date.isAfter(lastDayOfMonth); date = date.plusDays(1)) {
            // 格式化日期并添加到列表
            daysList.add(date.format(formatter));
        }

        return daysList;
    }

}
